//
// Created by root on 2019/9/26.
//

#include "AOADev.h"
#include "AOAaudio.h"
#include <cstdio>
#include "Manager.h"
#include "AOAManager.h"

static const uint16_t GOOGLE_VID = 0x18D1;

bool AOADev::IsBelong(libusb_device *dev, int status) {
    libusb_device_descriptor deviceDescriptor = {0};
    if (m_spAudio && m_spAudio->isEqual(dev) && status == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) {
        return true;
    } else if (status == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
        if (m_spAudio) {
            return false;
        } else {
            int ret = 0;
            ret = libusb_get_device_descriptor(dev, &deviceDescriptor);
            if (ret < 0) {
                return false;
            }
            if (deviceDescriptor.idVendor == GOOGLE_VID) {
                switch (deviceDescriptor.idProduct) {
                    case PID_AOA_ACC_AU_ADB:
                    case PID_AOA_AU:
                        printf("MATCH 0x%04x 0x%04x\n", deviceDescriptor.idVendor, deviceDescriptor.idProduct);
                        return true;
                }
            }
        }
    }
    return false;
}


void AOADev::handle(libusb_device *device, int status, AOAManager *manager) {
    if (status == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
        try {
            AOAaudio *dev = new AOAaudio(device);
            m_spAudio.reset(dev);
            manager->attachAoaDevice(m_spAudio);
        } catch (string str) {
            cout << str << endl;
        }
    } else {
        if (m_spAudio->isEqual(device)) {
            manager->deattachAoaDevice();
            m_spAudio.reset();
        }
    }

}

